<?php

namespace App\Http\Controllers\Wx;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\User;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\Log;

class PayController extends Controller
{
    public function notify()
    {
        $config = config('wechat');
        $app = Factory::payment($config);
        return $app->handlePaidNotify(function ($message, $fail) {
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                Log::info('微信支付回调:' . var_export($message, 1));
                if ($message['result_code'] === 'SUCCESS') {
                    $order = Order::where('order_no', $message['out_trade_no'])->first();
                    $order->status = 1;
                    $order->save();
                    $this->sendOrderPayTmpMsg($order);
                }
                return true;
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
    }

    // 订单支付成功消息通知
    public function sendOrderPayTmpMsg($order)
    {
        $config = config('wechat');
        $app = Factory::officialAccount($config);
        $app->template_message->send([
            'touser' => $order->user()->openid,
            'template_id' => $config['template_id']['order_pay'],
            'url' => env('APP_URL') . '/#/pages/order/order?id=' . $order->id, //订单地址
            'data' => [
                'first' => "订单支付成功", //消息标题
                'keyword1' => $order->order_no, //订单编号
                'keyword2' => $order->title, //商品名称
                'keyword3' => $order->amount, //订单总价
                'keyword4' => Order::$EnumStatus[$order->status], //订单状态
                'keyword5' => $order->created_at, //下单时间
                'remark' => '点击查看订单详情.',
            ],
        ]);
    }
}
